<template>
  <el-dialog title="品质得分计算" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="500px" @closed="$refs.form.resetFields()">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="btnLoading">
      <el-form-item label="选择月份" prop="countMonth">
        <el-date-picker v-model="yearMonth" type="month" placeholder="选择月份" value-format="yyyy-MM" :clearable="false" style="width: 100%" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button loading v-if="btnLoading">正在统计中</el-button>
      <el-button type="primary" @click="btnSubmit" v-else>确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 品质得分计算
import { debounce } from '@/utils'
import { calcQualityScore } from '@/api/statement/trdQc'
export default {
  props: { value: { type: Boolean, default: false } },
  data() {
    const currYearFirstDay = +new Date(new Date().Format('yyyy/01/01 00:00:00'))
    const firstDay = +new Date(new Date().Format('yyyy/MM/01 00:00:00'))
    const lastMonth = new Date(firstDay - 1).Format('yyyy-MM')
    return {
      btnLoading: false,
      form: { countYear: '', countMonth: '' },
      rules: { countMonth: [{ required: true, message: '请选择月份' }] },
      yearMonth: lastMonth,
      datePickerOpts: { disabledDate: time => time < currYearFirstDay || time >= firstDay }
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    yearMonth: {
      immediate: true,
      handler(val) {
        const yMonth = (val || '').split('-')
        this.form.countYear = yMonth[0] || ''
        this.form.countMonth = yMonth[1] || ''
      }
    },
    show(val) {
      if (!val) return
      const firstDay = new Date().Format('yyyy/MM/01 00:00:00')
      this.yearMonth = new Date(new Date(firstDay) - 1).Format('yyyy-MM')
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
  },
  methods: {
    async onSubmit() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return

      const opt = { ...this.form }
      this.btnLoading = true
      const res = await calcQualityScore(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.$message.success('提交成功')
      this.show = false
      this.$emit('ok', this.yearMonth)
    }
  }
}
</script>
